package com.yuantu.judiciary.serviceimpl;

import cn.hutool.core.util.URLUtil;
import com.alipay.api.AlipayConfig;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.page.Client;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.google.gson.Gson;
import com.yuantu.judiciary.model.dto.AddOrderDTO;
import com.yuantu.judiciary.service.IApiQrcodeAliPayService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.UUID;


@Service
@Slf4j
@RequiredArgsConstructor
public class ApiQrcodeAliPayServiceImpl implements IApiQrcodeAliPayService {


    private static final Gson GSON = new Gson();
    public static Config open_config;

    public static AlipayConfig alipayConfig;
    public static final String PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi/7rUBi4mm2rHzSW0BLey52A69zvbXiE7gz0bvqSKKJSSpLdvBZxhseQBSuUoaOSNzmna5ov1uu0pYC1vWGHsf7YjzcrAl8aYBL+wpVAsjij+fLTeftYleVZZPjIZfGtrggDuO3L4vVrmyszOqRFS9063jy4xnfYsBwXJjmaw2vmXx6BFE+WKAmytgcopk44Jt9HZqezRtV0HcuMnBYfXW1s/9/blqNpphzpk8tWBeb9/kE0gZ2+SkLqU2Gpnn/ImeOWRs5yDKYAOYDec8AAABPGo6F3MRNAX2OSkhce1lnZV9VQvwiotbg5Az8IftwYWVyTXPqOfv/++kj5psyPnQIDAQAB";
    // public static final String RETURN_URL = "https://admin.njxnet.com/pay/result";
    public static final String RETURN_URL = "https://admin.njxnet.com/judicial-data-aio/pages/view/redirect";

    public static Config getOptions() {
        if (open_config == null) {
            Config config = new Config();
            config.protocol = "https";
            config.gatewayHost = "openapi.alipay.com";
            config.signType = "RSA2";
            config.appId = "2021004108624309";
            config.merchantPrivateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCX2eLcNJr+0R8oaELOmk+iiVXA1bOrI6iVAiJAM56icWDIJ9boG57JOPOSPXv1NjrtecRdAWePxkCRePUzLbkiy7zELotHktXTruyGQJSzDuHDIAo686SONlu5jT886o8foPYRrMVi3m/e/Y1c1VcE7qVt0i6BGgUgLkwI/8/6asvAp1pwgw7IlLRvDK+nrS+X0zad6vC0RrZcTo5/YaRCDvdxfJsIzPElRbddy8TfyblXk/RtgWjP1AnnLcz/tHItrt75iep/Ij8lDJ6S2tea4XBjzFtwrG1zmE+livATl6U6HFvNUu0U63vD8PzE9JnP2IknS6DQWfHI9vq4QFYtAgMBAAECggEAHu6tfbnhkOK8fBiw8zEP48YiB8QAc24yGxhyLa3WNLTvyBYFewaVU9wcEcAgjhTb8CAL1f5BQFJcOMXw/NnliqcB7tykVpIcqKBLYhWptMflSUAvlU6oSKfeC3AwX5JQUVsShQsysi8pjr0LnMuAjGqonDRicL4CKUoFBxhFH3dtTOOkbBeCUhWl2fBAareZ1H9b/jjMg/5eCUXpx1rNTg6dkR1zeWfPvTh8BmUtq0CQQSzXuGnkL2q1JysBQa1aWZEUt2Y9m+mL1qiJfuXaL1hQ2x8R2NjRoHHpUlR99qNB/hPq5SHznlEb2XVUgu9cOzUNhjQrmNNwmTSTzwaHqQKBgQDRa9Vp6TvGbZi3ffPbDzvU4EhcLy38q3Co0hrKaM7PYWYpa4I9zdXATuRqtZOzUGnUOGGAHTcNB6avmR7aasDNBy1HkILgj/ehDhRbbvcF8Tvj/pFn8lvYgVeq70zeqb8KYgae5LfR536FzZ3WDe+zsawbI5wMJM1CYBWmj924PwKBgQC5oBZLz7oP/FUBIU22DHUaNPgb3oToIVOAfOUfw33qwpfInvHgiAdQplvoASJmAMb02emHqEcMe6+fr6lOddYm4Ldk2mC5lXBYqyepluHD/IQQLxQey2O/r0KkZoMYmhuh1j7ozTTOi31B2Z1mwf2DT+Q8tTkxFszlx9E9Yl32kwKBgDeybEIMy98MSu+SSgba2FjXhacuzRZEKmRb7NAka8xv5RHjC/KQCedplAplXHD2VA8jJ5tBKeEHReex26jPd5OP8xTzdDtxTrTA390pd/1WmU0b6WQx6wd77usBVfpqPuruA0DDJ7hlzxqbAv1pG3U5LcLSB7CbIRQkJd30qU1VAoGBAJn+TiDsnt4eJuL+HvsVUJzCLsboDniJFT313xs/0hlNACCmg+ES2Ia2zG4nasMWh/efRFaPawnXHnaqgxmdNmEgceSQKkgryn002H2ft4Ig3eqTM+zsLL9cBTxf8wgY6S2UkLIPc2yaWfqkLymNa+RhBea7LUwlLyy9XT/AeFVTAoGAbDxZzdNKRfhwiJNlhsB5sutgew8b8VSygXYPQgoG/yzHvSKe4UygcrgJggAl6xNRoNFgkVF1QDGSAG4kak7WFjDo4M878Qgsg392RZfllKy45nxBfL91yPGogMAnsy+3kBQZRP0stRbabIXlCua/yZm6PTTYjtFf78mvrSinnhQ=";
            config.alipayPublicKey = PUBLIC_KEY;
            //可设置异步通知接收服务地址（可选）
//            config.notifyUrl = "https://cxb.learncoder.com:8901/api/order/notify/app/ali";
            config.notifyUrl = "https://admin.njxnet.com:8901/api/order/notify/code/ali";
            //config.notifyUrl = "http://yuantu.natapp1.cc/api/order/notify/code/ali";
            //可设置AES密钥，调用AES加解密相关接口时需要（可选）
            config.encryptKey = "7qe0WUf9GVnfj/5qPGpmNA==";
            return config;
        } else {
            return open_config;
        }
    }


    @Override
    public String addOrder(AddOrderDTO data) {

        Factory.setOptions(getOptions());
        try {
            Client pageClient = Factory.Payment.Page();
            pageClient.optional("qr_pay_mode", 4);
             pageClient.optional("qrcode_width", 180);
            Date now = new Date();
            LocalDateTime localNow = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            LocalDateTime twoMinutesLater = localNow.plusMinutes(2);
            Date dateTwoMinutesLater = Date.from(twoMinutesLater.atZone(ZoneId.systemDefault()).toInstant());
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            pageClient.optional("time_expire", dateFormat.format(dateTwoMinutesLater));
            AlipayTradePagePayResponse response = pageClient.pay(data.getName(), data.getTradeNo(),
                    data.getTotalPrice().toString(), RETURN_URL);
            if (ResponseChecker.success(response)) {
                return response.getBody();
            } else {
                log.info("二维码支付宝支付-创建订单失败，返回值：{}", response.getBody());
            }
        } catch (Exception e) {
            log.error("二维码支付宝支付-创建订单异常，原因：" + e.getMessage(), e);
        }
        return "";
    }


    @Override
    public LinkedHashMap<String, String> callOrder(HttpServletRequest request) {
        Factory.setOptions(getOptions());
        try {
            BufferedReader br = request.getReader();
            String str;
            StringBuilder sb = new StringBuilder();
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            //回调的待验签字符串
            String params = URLUtil.decode(sb.toString(), "utf-8");
            //对待签名字符串数据通过&进行拆分
            String[] temp = params.split("&");
            LinkedHashMap<String, String> map = new LinkedHashMap<>();
            //把拆分数据放在map集合内
            for (int i = 0; i < temp.length; i++) {
                //通过"="号分割成2个数据
                String[] arr = temp[i].split("=", 2);
                //再开辟一个数组用来接收分割后的数据
                String[] tempAagin = new String[arr.length];
                for (int j = 0; j < arr.length; j++) {
                    tempAagin[j] = arr[j];
                }
                map.put(tempAagin[0], tempAagin[1]);
            }
            log.info("支付回调构造参数: {}", map);
            String outTradeNo = map.get("out_trade_no");
            String tradeStatus = map.get("trade_status");
            log.info("二维码支付宝支付-回调信息-订单：{}，交易状态：{}", outTradeNo, tradeStatus);
            boolean verifyNotify = AlipaySignature.rsaCheckV1(map, PUBLIC_KEY, "utf-8", "RSA2");
            log.info("二维码支付宝支付-验签结果: {}", verifyNotify);

            if (Boolean.TRUE.equals(verifyNotify)) {
                return map;
            } else {
                log.info("二维码支付宝支付-验签失败，回调参数: {}", params);
            }
        } catch (Exception e) {
            log.error("二维码支付宝支付-验签异常，原因：" + e.getMessage(), e);
        }
        return null;
    }
}
